<template>
  <div>
    <avue-crud
    v-if="option.column"
    :page="page"
    :data="data.data"
    :option="option"
    @row-save="create"
    @row-update="update"
    @row-del="remove"
    @on-load="pageChange"
    @sort-change="changeSort"
    @search-change="search"
    @upload-before="uploadBefore"
    ></avue-crud>
  </div>
</template>

<script lang="ts">
import { Vue, Component, Prop } from "vue-property-decorator";

@Component({})
export default class ResourceList extends Vue {
  @Prop(String) resource!:string
  data: any = {};
  option: any = {}
  page: any = {}
  query: any= {
    limit: 5,
    page: 1,
  }

  async fetch() {
    const res = await this.$http.get(`${this.resource}`, {params: {query: this.query}});
    this.data = res.data;
    const {total, page} = res.data
    this.page = {total, currentPage: page, pageSize: 10, pageSizes: [5, 10, 15, 20, 50], pageCount: 3}
  }

  async pageChange({currentPage, pageSize}) {
    this.query = {
      limit: pageSize,
      page: currentPage
    }
    this.fetch()
  }

  async changeSort({prop, order}) {
    order? this.query.sort = {
      [prop]: order === 'ascending'? 1 : -1
    } : null
    this.fetch()
  }

  async search(where:any,done:any){
    for(let k in where) {
      const field = this.option.column.find((v: any) => v.prop === k && v.regex)
      field? where[k] = {$regex: where[k]}: null
    }
    this.query.where = where
    this.fetch()
    done()
  }

  async uploadBefore(file:any, done:any, loading:any, column:any) {
    // const newFile = new File([file], '')
    console.log(file, done, loading, column)
    const formData = new FormData()
    formData.append('file', file)
    await this.$http.post('upload', formData)
    done()
  }

  async fetchOption() {
    const res = await this.$http.get(`${this.resource}/option`);
    this.option = res.data;
  }
  async create(row: any, done: any, loading: any) {
    console.log(loading)
    await this.$http.post(`${this.resource}`, row)
    this.$message.success('创建成功')
    this.fetch()
    done()
  }

  async update(row: any,index: any, done: any, loading: any) {
    const {$index, ...data} = row
    console.log($index, index, loading)
    await this.$http.put(`${this.resource}/${row._id}`, data)
    this.$message.success('更新成功')
    this.fetch()
    done()
  }
  async remove(row: any) {
      try {
          await this.$confirm('是否确认删除？')
      } catch (e) {
          return 
      }
      await this.$http.delete(`${this.resource}/${row._id}`)
      this.$message.success('删除成功')
      this.fetch()
  }
  created() {
    this.fetchOption();
    this.fetch();
  }
}
</script>

<style></style>
